<template>
  <div class="increase" v-loading="loading">
    <div class="top">
      <div class="search">
        <div class="contition">
          <div class="wrap_time">
            <date-time type="noDay" initShow="month" :query="query" :isShowCon="false"></date-time>
            <el-button type="primary" class="primary_btn fr find" v-on:click.stop="search">{{$t('public.search2')}}</el-button>
            <div class="clear"></div></div>
        </div>
      </div>
      <affix :label="title"></affix>
    </div>
    <div :id="id">
      <el-row class="ichars">
        <highcharts :options="highchartsOptions"></highcharts>
        <div class="notes">
          <span class="light">{{$t('report.hicharsNotes')}}: <span></span>{{$t('report.hicharsLight')}}</span>
          <span class="dark"><span></span>{{$t('report.hicharsDark')}}</span>
        </div>
      </el-row>
      <div class="tab">
        <div class="export">

          <!-- <el-button class="primary_btn fr report_excel_btn"
            v-if="$store.getters.exportFromEnd"
            @click.stop="exportXls"
          >{{$t('report.exportXls')+($store.state.xlsxExportMode==='Both'?'(旧)':'')}}</el-button> -->

          <el-button class="primary_btn fr report_excel_btn"
            @click.stop="exportXlsx"
          >{{$t('report.exportXls')}}</el-button>

          <el-button class="primary_btn fr pdf" @click.stop="exportPdf">{{$t('report.exportPDF')}}</el-button>
        </div>
        <report-table :sum="totalData" :data="tableData" :config="headOptions.Config"></report-table>
      </div>
    </div>
    <el-dialog :close-on-click-modal="false" modal-append-to-body lock-scroll top="10%" :title="$t('report.reportExportHelp')" :visible.sync="dialogVisible" width="30%">
      <span>{{$t('report.reportExportTipTitle')}}</span>
      <span slot="footer" class="dialog-footer">
        <el-button class="primary_btn" @click="dialogVisible = false">{{$t('public.cancel')}}</el-button>
        <el-button class="primary_btn" type="primary" @click="confirm">{{$t('public.confirm')}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import affix from '../../../ui-modules/affix/Affix.vue'
  import dateTime from '../base/datetime.vue'
  import reportTable from '../base/reportTable.vue'
  import { deepClone } from '@/utils/m7Utils.js'
  import { exportReportPdf, headOptionsToXlsxHeaders, searchTime, colorConfigArr } from '@/utils/reportUtils.js'
  import * as XlsxUtil from 'src/utils/XlsxUtil.umd.js'
  import {sortBy} from 'lodash'

  export default {
    name: 'customer_report_increase',
    data () {
      return {
        id: 'customer_report_increase',
        title: this.$t('report.customerReportIncrease'),
        loading: false,
        query: {},
        dialogVisible: false,
        timeType: 'month',
        sourceOptions: [],
        serverData: [],
        headOptions: { Config: [], data: [] },
        highchartsDefaultOptions: {
          chart: { type: '', animation: false },
          colors: colorConfigArr,
          xAxis: {
            categories: [],
            title: {
              enabled: true,
              text: '',
              style: { fontWeight: 'normal' }
            }
          },
          yAxis: {
            gridLineColor: '#e6e6e6',
            allowDecimals: false,
            title: { text: '' },
            showEmpty: false
          },
          title: { text: this.$t('report.customerReportIncrease') },
          legend: { align: 'center', verticalAlign: 'top', y: 30 },
          tooltip: {
            pointFormat: '<span style="color:{point.color}">\u25CF</span> {series.name}: <b>{point.y}{point.valueSuffix}</b><br/>',
            shared: true
          },
          credits: { enabled: false },
          series: []
        }
      }
    },
    components: {
      affix,
      dateTime,
      reportTable
    },
    computed: {
      tableData () {
        return this.getTableData(this.serverData)
      },
      totalData () {
        return this.getTotalData(this.serverData)
      },
      highchartsOptions () {
        let options = deepClone(this.highchartsDefaultOptions)
        if (!this.serverData || this.serverData.length === 0) {
          return options
        }

        let headerConfig = this.headOptions.Config || []
        let datas = this.serverData
        let categoriesArray = []
        let seriesArray = []

        headerConfig.forEach(item => {
          if (!item.show) {
            return
          }
          if (item.name === 'day') {
            return
          }
          let serie = { name: item.displayname, data: [], valueName: item.name }
          seriesArray.push(serie)
        })

        for (let i = 0; i < datas.length; i++) {
          categoriesArray.push(this.formatReportTime(datas[i].day))
          for (let j = 0; j < seriesArray.length; j++) {
            seriesArray[j].data.push(datas[i][seriesArray[j].valueName] || 0)
          }
        }

        options.xAxis.categories = categoriesArray
        options.series = seriesArray

        return options
      }
    },
    methods: {
      getTableData (serverData) {
        if (!serverData || serverData.length === 0) {
          return []
        }

        let data = deepClone(serverData)
        data.forEach(item => {
          item.day = this.formatReportTime(item.day)
          for (let i = 0; i < this.sourceOptions.length; i++) {
            if (!item[this.sourceOptions[i].key]) {
              item[this.sourceOptions[i].key] = 0
            }
          }
        })

        return data
      },
      getTotalData (serverData) {
        if (!serverData || serverData.length === 0) {
          return []
        }
        let total = deepClone(this.total)
        total.day = this.$t('report.total')
        return [total]
      },
      getSourceName (id) {
        for (let i = 0; i < this.sourceOptions.length; i++) {
          if (this.sourceOptions[i].key === id) {
            return this.sourceOptions[i].name
          }
        }
        return ''
      },
      formatReportTime (reportTime) {
        if (this.timeType === 'month') {
          return `${reportTime.substring(0, 4)}-${reportTime.substring(4, 6)}-${reportTime.substring(6, 8)}`
        } else if (this.timeType === 'year') {
          return `${reportTime.substring(0, 4)}-${reportTime.substring(4, 6)}`
        }
      },
      getSearchQueryData () {
        let data = {
          reportType: this.id,
          account: this.$store.state.session.user.account,
          query: { reportType: this.id },
          keys: this.sourceOptions.filter(source => source.key !== 'unknow').map(source => source.key)
        }
        let query = deepClone(this.query)

        data.query = Object.assign({}, data.query, query)
        return data
      },
      search () {
        var data = this.getSearchQueryData()
        if (!data) {
          return
        }
        var query = data.query
        this.loading = true
        this.$store.dispatch('queryCustomerIncreaseReport', data).then((res) => {
          this.loading = false
          // 表头
          this.headOptions = {
            Config: [
              { order: 1, name: 'day', displayname: this.$t('public.time'), show: true },
              ...this.sourceOptions.map((source, index) => ({ order: index + 2, name: source.key, displayname: source.name, show: true }))
            ]
          }
          let data = res.data
          this.total = res.total
          this.timeType = query.timeType
          this.serverData = deepClone(sortBy(data, 'day')) || this.serverData
        })
      },
      exportXlsx () {
        var data = this.getSearchQueryData()
        if (!data) {
          return
        }
        var query = data.query
        this.loading = true
        this.$store.dispatch('queryCustomerIncreaseReport', data).then((res) => {
          this.loading = false
          this.timeType = query.timeType
          var headOptions = {
            Config: [
              { order: 1, name: 'day', displayname: this.$t('public.time'), show: true },
              ...this.sourceOptions.map((source, index) => ({ order: index + 2, name: source.key, displayname: source.name, show: true }))
            ]
          }
          let data = res.data
          this.total = res.total
          var serverData = deepClone(sortBy(data, 'day')) || []
          var sum = this.getTotalData(serverData, headOptions)

          var tableData = this.getTableData(serverData).concat(sum)
          var headers = headOptionsToXlsxHeaders(headOptions.Config)

          var dh = XlsxUtil.getDownloadHelper(headers, tableData)
          var timeStamp = XlsxUtil.dateFormat(new Date(), 'yyyy-MM-dd hh-mm-ss')
          dh.download(this.$t('report.customerReportIncrease') + timeStamp)
        })
      },
      exportXls () {
        let data = {
          Method: 'exportCustomerIncrease',
          Query: { reportType: this.id, user: this.$store.state.session.user._id }
        }
        let query = deepClone(this.query)
        data.Query = Object.assign({}, data.Query, query)
        this.$store.dispatch('exportCustomerIncreaseReport', data)
      },
      exportPdf () {
        this.dialogVisible = true
      },
      confirm () {
        this.dialogVisible = false
        exportReportPdf({title: this.$t('report.customerReportIncrease') + searchTime(this.query), id: this.id})
      }
    },
    beforeMount () {
      this.$store.dispatch('getCache', { type: 'custTmpls' }).then(custTmpls => {
        this.sourceOptions = custTmpls[0].source.filter(source => source.key !== 'unknow')
        this.sourceOptions.push({ key: 'unknow', name: this.$t('customer.unknownSource') })
        this.search()
      })
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../assets/common.styl"
  #customer_report_increase
  .increase
    .deploy
      .tex
      .te
        cursor pointer
      .set
        margin-right 10px
        position relative
        top 2px
</style>
